//
//  MyCareViewController.m
//  CommunityApp
//
//  Created by 秦乾龙 on 16/12/30.
//  Copyright © 2016年 秦乾龙. All rights reserved.
//

#import "MyCareViewController.h"
#import "ZYButton.h"
#import "NavView.h"
#import "UIButton+WebCache.h"
#import "UIImageView+WebCache.h"
#import "HisHomePageViewController.h"
#import "User.h"
#define kScreenW [UIScreen mainScreen].bounds.size.width
#define kScreenH [UIScreen mainScreen].bounds.size.height
#define kScale   ([UIScreen mainScreen].bounds.size.width)/750
@interface MyCareViewController ()<UITextFieldDelegate,UITextViewDelegate,UITableViewDelegate,UITableViewDataSource>
@property (nonatomic,retain) UITableView *mainTableView;
@property (nonatomic,retain) NSMutableArray *allDataArr;
@property (assign, nonatomic) BOOL pageToEnd;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) NSInteger limit;
@end

@implementation MyCareViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.limit = 5;
    [self setUI];
}
- (void) setUI
{
    self.navigationItem.titleView = [ViewFactory makeNavigationTitle:@"我的关注"];
    
    UIBarButtonItem *backBtn = [ViewFactory makeNavigationBackWhite:self action:@selector(backClick)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    _mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0,kScreenW , kScreenH-64) style:UITableViewStyleGrouped];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    [self.view addSubview:_mainTableView];
    [self addRefreshHeader:_mainTableView];
//    [self addLoadMoreFooter:_mainTableView];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self request];
    
}
//下拉刷新
- (void)refresh {
    [super refresh];
    [self request];
}
//上拉加载
//- (void)loadMore {
//    if (self.pageToEnd) {
//        [ViewFactory showInfoMsg:@"没有下一页了！"];
//        [_mainTableView.footer endRefreshing];
//        return;
//    }
//    
//    DYBaseRequest *request = [DYBaseRequest new];
//    NSString *url = [NSString stringWithFormat:@"%@/userCenter/getUserAttountByUserId?page=%ld&limit=%ld", APIYIGOU, self.page,self.limit];
//    DYLog(@".....%ld",self.page);
//    request.requestUrl =  [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//    [ViewFactory showLoading];
//    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
//        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
//        NSArray *array = allDic[@"data"][@"list"];
//        DYLog(@"66666%@",array);
//        if (array.count == 0) {
//            [ViewFactory showInfoMsg:@"没有下一页了！"];
//            
//        }
//        else if (array.count<_limit)
//        {
//            self.pageToEnd = YES;
//        }
//        self.page += 1;
//        DYLog(@".....%ld",array.count);
//        [_allDataArr addObjectsFromArray: array];
//        DYLog(@".....%ld",_allDataArr.count);
//        [ViewFactory dismissLoading];
//        [_mainTableView reloadData];
//        [_mainTableView.footer endRefreshing];
//    } error:^(YTKBaseRequest *request) {
//        [_mainTableView.footer endRefreshing];
//    } failure:^(YTKBaseRequest *request) {
//        [ViewFactory showErrorStrMsg:NETWORK_ERR];
//        [_mainTableView.footer endRefreshing];
//    }];
//}
- (void)request
{
    self.page = 1;
    self.pageToEnd = NO;
    NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/getUserAttountByUserId?page=%ld&limit=%ld",APIYIGOU,self.page,self.limit];
    DYBaseRequest *request = [DYBaseRequest new];
    request.requestUrl = urlStr;
    [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
        NSLog(@"122222%@",allDic);
        _allDataArr = [NSMutableArray array];
        [_allDataArr addObjectsFromArray: allDic[@"data"][@"list"] ];
        
        [_mainTableView reloadData];
        self.page+=1;
        if (_allDataArr.count == 0) {
            [self showNoData];
        } else {
            [self hideNoData];
        }
        [_mainTableView.header endRefreshing];
    } error:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
    } failure:^(YTKBaseRequest *request) {
        [_mainTableView.header endRefreshing];
        [ViewFactory showErrorStrMsg:NETWORK_ERR];
    }];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _allDataArr.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell =[[NSBundle mainBundle ]loadNibNamed:@"ZYTableViewCell" owner:nil options:nil][0];
    }
    //设置cell点击背景色不变
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    User *user = [[User alloc]initWithDic:_allDataArr[indexPath.section]];
    CGFloat headerImageH = 84*kScale;
    UIImageView *headerImage = [[UIImageView alloc]init];
    headerImage.frame = CGRectMake(30*kScale, 40*kScale,headerImageH, headerImageH);
    //        [headerImage sd_setImageWithURL:shop[@"seller_logo"]];
    headerImage.layer.masksToBounds = YES;
    headerImage.layer.cornerRadius = 42*kScale;
//    headerImage.backgroundColor = [UIColor cyanColor];
    [headerImage sd_setImageWithURL:[NSURL URLWithString:user.headerImageUrl]];
    NSLog(@"99999%@",user.headerImageUrl);
    [cell addSubview:headerImage];
    UILabel *nameLable = [[UILabel alloc]init];
    nameLable.font = [UIFont systemFontOfSize:15];
    
    nameLable.text = user.name;
    nameLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y, kScreenW-(headerImageH+3*30*kScale), 36*kScale);
    [cell addSubview:nameLable];
    UILabel *introLable= [[UILabel alloc]init];
    introLable.font = [UIFont systemFontOfSize:12];
    introLable.text = [NSString stringWithFormat:@"%@",user.personSign];
    //        CGSize priceSize = [introLable sizeThatFits:CGSizeMake(MAXFLOAT, 40*kScale)];
    introLable.frame = CGRectMake(headerImageH+2*30*kScale, headerImage.frame.origin.y+headerImageH-40*kScale, kScreenW-3*30*kScale-50*kScale-178*kScale-headerImageH, 36*kScale);
    introLable.textColor = ZallColorFromRGB(0x616161);
    [cell addSubview:introLable];
//    ZYButton *careBtn= [[ZYButton alloc]init];
//    careBtn.font = [UIFont systemFontOfSize:18];
//    
//    [careBtn setTitle:@"取消关注" forState:UIControlStateNormal];
//    [careBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//    [careBtn addTarget:self action:@selector(cancelClick:) forControlEvents:UIControlEventTouchUpInside];
//    //        CGSize quXiaoSize = [quXiaoBtn sizeThatFits:CGSizeMake(MAXFLOAT, 40*kScale)];
//    careBtn.frame = CGRectMake(kScreenW -30*kScale-104*kScale, 58*kScale, 104*kScale, 48*kScale);
//    [cell addSubview:careBtn];
    ZYButton *stateBtn = [[ZYButton alloc]initWithFrame:CGRectMake(kScreenW-30*kScale-178*kScale, 61*kScale, 178*kScale,60*kScale)];
    stateBtn.followUserId = user.userId;
    stateBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    stateBtn.tag = indexPath.section;
    stateBtn.layer.cornerRadius  = 8*kScale;
    stateBtn.layer.masksToBounds = YES;
//    stateBtn.layer.borderWidth = 1.0f;
//    stateBtn.layer.borderColor = [UIColor lightGrayColor].CGColor;
    stateBtn.backgroundColor = ZallColorFromRGB(0x1fa2b6);
    [stateBtn setTitle:@"取消关注" forState:UIControlStateNormal];
    [stateBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [stateBtn addTarget:self action:@selector(cancleCareClick:) forControlEvents:UIControlEventTouchUpInside];
    stateBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [cell addSubview:stateBtn];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
        return  164*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return  0.01;
    }
    
    return 20*kScale;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    User *user = [[User alloc]initWithDic:_allDataArr[indexPath.section]];
    HisHomePageViewController *hisHome = [[HisHomePageViewController alloc]init];
    hisHome.userid = user.userId;
    [self.navigationController pushViewController:hisHome animated:YES];
}
//取消关注
- (void)cancleCareClick:(ZYButton*)sender
{
    if (sender.selected==NO) {
        NSString *urlStr = [NSString stringWithFormat:@"%@/userCenter/qxAttountByUserId?follow_obj_type=00&follow_obj_id=%@",APIYIGOU,sender.followUserId];
        DYBaseRequest *request = [DYBaseRequest new];
        request.requestUrl = urlStr;
        [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            //        NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
            //        [_allDataArr removeObjectAtIndex:sender.tag];
            //        [_mainTableView reloadData];
            [ViewFactory showSuccess:@"取消关注成功"];
            [sender setTitle:@"＋关注" forState:UIControlStateNormal];
            sender.selected = YES;
        } error:^(YTKBaseRequest *request) {
            
        } failure:^(YTKBaseRequest *request) {
            [ViewFactory showErrorStrMsg:NETWORK_ERR];
        }];

    }
    else
    {
        DYBaseRequest *request = [DYBaseRequest new];
        
        NSString *url = [NSString stringWithFormat:@"%@/hytribe/setConcern?follow_obj_id=%@", APIYIGOU, sender.followUserId];
        request.requestUrl = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        [request dyBgStartWithCompletionBlockWithSuccess:^(YTKBaseRequest *request) {
            NSDictionary *allDic = [NSDictionary changeType:request.responseJSONObject];
            NSLog(@"1111111%@",allDic);
            
            [ViewFactory showSuccess:@"关注成功"];
            [sender setTitle:@"取消关注" forState:UIControlStateNormal];
            sender.selected = NO;
        } error:^(YTKBaseRequest *request) {
            NSData *JSONData = [request.responseString dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
            [ViewFactory showErrorStrMsg:[responseJSON objectForKey:@"message"]];
        } failure:^(YTKBaseRequest *request) {
            [ViewFactory showErrorStrMsg:NETWORK_ERR];
            
        }];
    }
}

- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
